package MyThread;

public class MyThread {
    // join 方法
    public static void main1(String[] args) throws InterruptedException {
        TestJoin t = new TestJoin();
        t.start();
        for (int i = 1; i <= 10; i++) {
            System.out.println("猪八戒吃了 "+i+" 块叉烧~");
            if (i == 7){
                System.out.println("猪八戒决定让师傅先吃");
                t.join();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 守护线程
    public static void main2(String[] args) throws InterruptedException {
        Deamon t = new Deamon();
        t.setDaemon(true);
        t.start();
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+"在惬意的生活~~");
            Thread.sleep(1000);
        }
    }

    // 线程的状态
    public static void main3(String[] args) throws InterruptedException {
        ThreadState t = new ThreadState();
        System.out.println(t.getState());
        t.start();
        while(Thread.State.TERMINATED != t.getState()){
            System.out.println(t.getState());
            Thread.sleep(500);
        }
        System.out.println(t.getState());
    }

    // 线程同步 Synchronized
    // 解决售票超卖问题
    public static void main(String[] args) {
        SellTicket t = new SellTicket();
        new Thread(t).start();
        new Thread(t).start();
        new Thread(t).start();
    }
}

class TestJoin extends Thread{
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println("唐三藏吃了 "+i+" 个胡萝卜~");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


class Deamon extends Thread{
    @Override
    public void run() {
        while(true){
            System.out.println("~~~~` 守护线程 `~~~~");

            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class ThreadState extends Thread
{
    @Override
    public void run() {
        while (true){
            for (int i = 0; i <= 10; i++) {
                System.out.println("我的回应是无限的，我的行动是有限的~");
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            break;
        }
    }
}





